package com.admin.education.domain.eventHandlers;

import com.admin.education.dataTransferObject.userAnswerSheet.Request.AnswerSheet;
import com.admin.education.dataTransferObject.userAnswerSheet.Request.CreateUserAnswersSheetRequest;
import com.admin.education.domain.event.CreateUserAnswerSheetEvent;
import com.admin.education.domain.event.CreateUserRecordEvent;
import com.admin.education.models.*;
import com.admin.education.models.Mapper.UserAnswerSheetModelMapper;
import com.admin.education.repositories.*;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class UserListener {
    private QUserInformation qUserInformation;

    public UserListener() {
        qUserInformation = QUserInformation.userInformation;
    }

    @Autowired
    private EventBus eventbus;
    @Autowired
    private UserInformationRepository userInformationRepository;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private UserRecordRepository userRecordRepository;
    @PostConstruct
    public void init() {
        this.eventbus.register(this);
    }

    @Subscribe
    public void onRefreshIntegrals(CreateUserAnswerSheetEvent createUserAnswerSheetEvent) {

    }

    @Subscribe
    public void onCreateUserRecord(CreateUserRecordEvent createUserRecordEvent) {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(defaultTransactionDefinition);

        UserInformation userInformation = userInformationRepository.selectFrom(qUserInformation).where(qUserInformation.id.eq(createUserRecordEvent.getUserInformationId())).fetchFirst();
        if(null==userInformation)
            return;

        UserRecords userRecords = new UserRecords();
        userRecords.setCreateTime(new Date());
        userRecords.setRecord(userInformation.getName()+createUserRecordEvent.getRecord());

        userRecords.setUserInformation(userInformation);

        this.userRecordRepository.persist(userRecords);
        platformTransactionManager.commit(transactionStatus);
    }

}
